package com.app.twth.ui.b2ctrailer.submit;


import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.app.twth.BR;
import com.app.twth.R;
import com.app.twth.app.AppRouter;
import com.app.twth.base.BaseActivity;
import com.app.twth.databinding.ActivityB2cTrailerSubmitBinding;
import com.app.twth.databinding.DialogB2bTrailerBinding;
import com.app.twth.databinding.DialogOutboundRemoveTrackingBinding;
import com.app.twth.ui.b2ctrailer.B2CTrailer;
import com.app.twth.ui.b2ctrailer.B2CTrailerInitInfo;
import com.app.twth.ui.b2ctrailer.B2CTrailerViewModel;
import com.app.twth.ui.lpnphoto.lpn.LPNPhotoLPNAdapter;
import com.app.twth.utils.EditTextUtil;
import com.app.twth.utils.MyDialogUtil;
import com.app.twth.utils.Utils;

import java.util.ArrayList;
import java.util.List;

/**
 * @describe :
 */
public class B2CTrailerSubmitActivity extends BaseActivity<ActivityB2cTrailerSubmitBinding, B2CTrailerViewModel> {
    private String TAG = getClass().getSimpleName();

    B2CTrailerSubmitAdapter adapter;

    @Override
    protected void initListener() {
        viewModel.submitLiveData.observe(this, data -> {
            Intent intent = new Intent();
            setResult(RESULT_OK, intent);
            finish();
        });
        viewModel.detailListLiveData.observe(this, data -> {
            binding.tvOblpnList.setText("OBLPN List("+viewModel.detailListLiveData.getValue().size()+")");
            if (adapter!=null){
                adapter.setData(data, 0);
            }
        });
        viewModel.errorResultCode.observe(this, code -> {
            showHint((String) code);
        });
        viewModel.isLoading.observe(this, b -> {
            if (b.isShow()) {
                showProgressDialog(b.getMsg());
            } else {
                dismissProgressDialog();
            }
        });
    }

    protected String setTitle() {
        return "Trailer(Submit)";
    }

    @Override
    protected int initViewModelId() {
        return BR.viewModel;
    }

    @Override
    protected void initData() {
        setReset(getString(R.string.submit));

        Bundle bundle = getIntent().getBundleExtra(AppRouter.K_EXTRA);
        viewModel.b2cTrailerLiveData.setValue((B2CTrailer) bundle.getSerializable("B2CTrailer"));
        viewModel.infoMutableLiveData.setValue((B2CTrailerInitInfo) bundle.getSerializable("data"));

        if ((viewModel.b2cTrailerLiveData.getValue() != null) && (viewModel.b2cTrailerLiveData.getValue().getDetailList() != null)) {
            viewModel.detailListLiveData.setValue(viewModel.b2cTrailerLiveData.getValue().getDetailList());
        }
        if (viewModel.detailListLiveData.getValue() == null) {
            viewModel.detailListLiveData.setValue(new ArrayList<>());
        }
        binding.tvOblpnList.setText("OBLPN List("+viewModel.detailListLiveData.getValue().size()+")");
        binding.tvCode.requestFocus();
        binding.tvCode.setOnEditorActionListener(EnterListenter);
        adapter = new B2CTrailerSubmitAdapter(this, viewModel.detailListLiveData.getValue(), position -> {
            if (System.currentTimeMillis() - timeMillis < 500) {//两秒内触发一次
                return;
            }
            timeMillis = System.currentTimeMillis();

            showRemoveTrackingDialog(position, viewModel.detailListLiveData.getValue().get(position));
        });
        LinearLayoutManager oblpnLayoutManager = new LinearLayoutManager(this);
        oblpnLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        binding.rvOblpn.setLayoutManager(oblpnLayoutManager);
        binding.rvOblpn.setAdapter(adapter);

    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        bottomLayoutBinding.tvHint.setText("");
        initScan();
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        unScan();
    }


    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_scan:
                setScan();
                break;
            case R.id.tv_reset:
                binding.tvCode.setText("");
                List<String> obLpns = new ArrayList<>();
                for (B2CTrailer.DetailListDTO detailListDTO : viewModel.detailListLiveData.getValue()) {
//                    if (detailListDTO.getId() == null) {
                        obLpns.add(detailListDTO.getObLpn());
//                    }
//                    obLpns.add(detailListDTO.getObLpn());
                }
                if (obLpns.size() == 0) {
                    showHint("Please add OUTBOUND LPN");
                    return;
                }
                viewModel.b2cTrailerSubmit(obLpns);
                break;
            case R.id.layout_trailer:
                if (viewModel.infoMutableLiveData.getValue().getPendingObLpnList() == null || viewModel.infoMutableLiveData.getValue().getPendingObLpnList().size() == 0) {
                    return;
                }
                showPendinglDialog();
                break;
        }
    }


    @Override
    public void getScanninCode() {
        super.getScanninCode();
        binding.tvCode.setText(barcodeStr);
        setLPNLoaded(barcodeStr);
    }

    private TextView.OnEditorActionListener EnterListenter = new TextView.OnEditorActionListener() {

        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                barcodeStr = binding.tvCode.getText().toString();
                //关闭软键盘
                EditTextUtil.hideInput(mContext);
                if (!Utils.isEmpty(barcodeStr)) {
                    setLPNLoaded(barcodeStr);
                }
            }
            return false;
        }
    };

    private void setLPNLoaded(String barcode) {
        if (viewModel.detailListLiveData.getValue() != null) {
            for (B2CTrailer.DetailListDTO detailListDTO : viewModel.detailListLiveData.getValue()) {
                if (detailListDTO.getObLpn().equals(barcode)) {
                    return;
                }
            }
        }
        viewModel.b2cTrailerCheckObLpn(barcode);
    }

    private AlertDialog dialogRemoveTracking;

    private void showRemoveTrackingDialog(int position, B2CTrailer.DetailListDTO detailListDTO) {
        dialogRemoveTracking = MyDialogUtil.getDialog(mContext, initRemoveTrackingDialogView(detailListDTO), Gravity.CENTER);
        dialogRemoveTracking.setCanceledOnTouchOutside(false);
        dialogRemoveTracking.show();
    }

    private View initRemoveTrackingDialogView(B2CTrailer.DetailListDTO detailListDTO) {
        DialogOutboundRemoveTrackingBinding dialogBinding = DialogOutboundRemoveTrackingBinding.inflate(getLayoutInflater());

        dialogBinding.tvContent.setText("Remove " + detailListDTO.getObLpn() + " form " + viewModel.b2cTrailerLiveData.getValue().getTrailerNo());
        dialogBinding.tvCancel.setOnClickListener(v -> {
            if (dialogRemoveTracking != null) {
                dialogRemoveTracking.dismiss();
            }
        });
        dialogBinding.tvConfirm.setOnClickListener(v -> {
            if (dialogRemoveTracking != null) {
                dialogRemoveTracking.dismiss();
            }
            if (detailListDTO.getId() == null) {
                viewModel.detailListLiveData.getValue().remove(detailListDTO);
                binding.tvOblpnList.setText("OBLPN List("+viewModel.detailListLiveData.getValue().size()+")");
                if (adapter != null) {
                    adapter.setData(viewModel.detailListLiveData.getValue(), -1);
                }
                return;
            }
            viewModel.b2cTrailerRemove(detailListDTO.getId());

        });
        return dialogBinding.getRoot();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private AlertDialog pendingDialog;

    private void showPendinglDialog() {
        pendingDialog = MyDialogUtil.getDialog(mContext, initPendingDialogView(), Gravity.CENTER);
        pendingDialog.setCanceledOnTouchOutside(true);
        pendingDialog.show();
    }

    private View initPendingDialogView() {
        DialogB2bTrailerBinding dialogBinding = DialogB2bTrailerBinding.inflate(getLayoutInflater());

        dialogBinding.tvTitle.setText("Pending OBLPN(" + viewModel.infoMutableLiveData.getValue().getPendingObLpnList().size() + ")");
        LPNPhotoLPNAdapter pendingAdapter = new LPNPhotoLPNAdapter(this, viewModel.infoMutableLiveData.getValue().getPendingObLpnList(), null);

        LinearLayoutManager layoutManager1 = new LinearLayoutManager(this);
        layoutManager1.setOrientation(LinearLayoutManager.VERTICAL);
        dialogBinding.recyclerview.setLayoutManager(layoutManager1);
        dialogBinding.recyclerview.setAdapter(pendingAdapter);

        dialogBinding.tvTitle.setOnClickListener(v -> {
            if (pendingDialog != null) {
                pendingDialog.dismiss();
            }
        });
        return dialogBinding.getRoot();
    }
}
